package com.yun.zf.admin.util;
import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;
import com.yun.zf.common.admin.domain.ZfPactPersonInfo;
import com.yun.zf.common.admin.domain.ZfPactRentInfo;
import com.yun.zf.common.admin.model.pact.PactTempMo;
import com.yun.zf.common.app.domain.ZfPact;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.math.BigDecimal;
import java.util.*;

@Component
public class PDFUtil {

    /**
     * 通过html的字符串转pdf
     * @param out
     * @param html
     * @throws IOException
     * @throws DocumentException
     */
    public static void createPdfByHtml(OutputStream out, String html) throws IOException, DocumentException {
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("/Users/wilson/logs/MSYH.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        renderer.layout();
        renderer.createPDF(out);
    }

    /**
     * 通过html的文件路径转pdf
     * @param out
     * @param htmlFilePath
     * @throws IOException
     * @throws DocumentException
     */
    public static void createPdfByUrl(OutputStream out,String htmlFilePath) throws IOException, DocumentException{
        ITextRenderer renderer = new ITextRenderer();
        String url = new File(htmlFilePath).toURI().toURL().toString();
        renderer.setDocument(url);
        // 解决中文支持问题
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("/Users/wilson/logs/MSYH.TTC", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //解决图片的相对路径问题
        //renderer.getSharedContext().setBaseURL("http://localhost:8080");//file:/e:/
        renderer.layout();
        renderer.createPDF(out);
    }

    public static void main(String[] args) {
        try {
            Configuration config = new Configuration();

            String path = "/Users/wilson/up/zf/zf_platform/zf-admin/src/main/resources/ftl";
            TemplateLoader templateLoader = new FileTemplateLoader(new File(path));
            config.setTemplateLoader(templateLoader);

            Template template = config.getTemplate("index.ftl", Locale.SIMPLIFIED_CHINESE);
            ZfPactPersonInfo personInfo = new ZfPactPersonInfo();
            personInfo.setName("张三");
            personInfo.setType(1);
            personInfo.setAddress("测试地址");
            personInfo.setCardNo("2334343");
            personInfo.setCitizenship("中国");
            personInfo.setCardType(1);
            personInfo.setEmail("111111@qq.com");
            personInfo.setIphone("199999999");
            personInfo.setSex("男");
            ZfPactPersonInfo personInfo1 = new ZfPactPersonInfo();
            personInfo1.setName("栗色");
            personInfo1.setType(2);
            personInfo1.setAddress("测试地址335");
            personInfo1.setCardNo("111111112334343");
            personInfo1.setCitizenship("中国");
            personInfo1.setCardType(2);
            personInfo1.setEmail("999999111111@qq.com");
            personInfo1.setIphone("1888888888");
            personInfo1.setSex("女");
            List<ZfPactPersonInfo> list = new ArrayList<>();
            list.add(personInfo);
            list.add(personInfo1);
            // 合同基本信息
            ZfPact pact = new ZfPact();
            pact.setCityName("武汉");
            pact.setRegionName("洪山区");
            pact.setStreetName("和平街道");
            pact.setArea(new BigDecimal("88"));
            pact.setCertType(1);
            pact.setIsDy(2);

            // 租赁部分
            ZfPactRentInfo rentInfo = new ZfPactRentInfo();
            rentInfo.setUseType("居住");
            rentInfo.setStartTime("2021-8-14");
            rentInfo.setEndTime("2022-8-13");
            rentInfo.setFrequency("Q");
            rentInfo.setPayType("O");
            rentInfo.setDeposit(new BigDecimal("2400"));
            rentInfo.setPartyA("1,2,3,4,5,6");
            rentInfo.setPartyB("1,2,3");
            rentInfo.setRemarks("(一)如甲方违约或者单方提出解除合同而违约的，应双倍返还乙方租赁押金，乙方单方违约或提出解除合同的，甲方有权没收乙 方支付的租赁押金并解除合同，乙方应付清所欠租金、水电费、物业管理费等应付费用。\n" +
                    "(二)因甲方未按约定履行维修义务造成乙方人身、财产损失的，甲方应承担赔偿责任。\n" +
                    "(三)甲方未按约定时间交付房屋或者乙方不按约定支付租金但未达到解除合同条件的，以及乙方未按约定时间返还房屋的，应按 月租金的3%标准支付违约金。");
            String [] pa = rentInfo.getPartyA().split(",");
            String [] pb = rentInfo.getPartyB().split(",");
            PactTempMo pt = new PactTempMo();
            for (String a: pa) {
                switch (a){
                    case "1":
                        pt.setS("1");
                        break;
                    case "2":
                        pt.setD("2");
                        break;
                    case "3":
                        pt.setK("3");
                        break;
                    case "4":
                        pt.setR("4");
                        break;
                    case "5":
                        pt.setW("5");
                        break;
                    case "6":
                        pt.setC("6");
                        break;
                }

            }
            PactTempMo pt1 = new PactTempMo();
            for (String b: pb) {
                switch (b){
                    case "1":
                        pt1.setS("1");
                        break;
                    case "2":
                        pt1.setD("2");
                        break;
                    case "3":
                        pt1.setK("3");
                        break;
                    case "4":
                        pt1.setR("4");
                        break;
                    case "5":
                        pt1.setW("5");
                        break;
                    case "6":
                        pt1.setC("6");
                        break;
                }

            }
            Map<String,Object> map = new HashMap<>();
            map.put("personInfos",list);
            map.put("isselected","2");
            map.put("pact",pact);
            map.put("rent",rentInfo);
            map.put("pa",pt);
            map.put("pb",pt1);
            StringWriter fileWriter = new StringWriter();
            //  FileWriter fileWriter = new FileWriter("src/main/resources/html/index.html");
            template.process(map, fileWriter);
            System.out.println(fileWriter.getBuffer());
            fileWriter.close();

            String outputFile = "/Users/wilson/logs/zf_2.pdf";
            OutputStream os = new FileOutputStream(outputFile);
            createPdfByHtml(os,fileWriter.getBuffer().toString());

            /*String str="<!DOCTYPE html>\n" +
                    "<html lang=\"zh_CN\" xmlns=\"http://www.w3.org/1999/html\">\n" +
                    "<head>\n" +
                    "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n" +
                    "    <title>SpringBoot 生成 html</title>\n" +
                    "    <style>\n" +
                    "        body {\n" +
                    "            font-family: \"Microsoft YaHei\";\n" +
                    "            font-size: 11px\n" +
                    "        }\n" +
                    "    </style>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "<div style=\"margin:0 auto;width:690px;height:auto;\">\n" +
                    "    <label>  <input type=\"checkbox\"  checked=\"checked\" />月 /</label>\n" +
                    "    <label><input name=\"Fruit\" type=\"checkbox\" value=\"\" />季 / </label>\n" +
                    "    <label><input name=\"Fruit\" type=\"checkbox\" value=\"\" />半年 / </label>\n" +
                    "</div>\n" +
                    "</body>\n" +
                    "</html>\n";
            String outputFile = "/Users/wilson/logs/zf_55.pdf";
            OutputStream os = new FileOutputStream(outputFile);
            createPdfByHtml(os,str);*/

         /*   String inputFile = "/Users/wilson/logs/index.html";
            String outputFile = "/Users/wilson/logs/zf_55.pdf";
            OutputStream os = new FileOutputStream(outputFile);
            createPdfByUrl(os,inputFile);
            os.close();*/
        }catch (Exception e){
            System.out.println(e.toString());
        }finally {

        }


    }
}
